// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// var receiverURL = 'ws://' + location.host + '/receiver';
var receiverURL = 'ws://localhost:3000/receiver';


window.addEventListener('DOMContentLoaded', function() {
  var base;

  var doc = $('#iframeId2')[0].contentWindow.document;
  // var doc = document;

  doc.ready = function() {
    console.log('read');
  };
  var mirror = new TreeMirror(doc, {
    createElement: function(tagName) {
      if (tagName == 'SCRIPT') {
        var node = doc.createElement('NO-SCRIPT');
        node.style.display = 'none';
        return node;
      }

      if (tagName == 'HEAD') {
        var node = doc.createElement('HEAD');
        node.appendChild(doc.createElement('BASE'));
        node.firstChild.href = base;
        return node;
      }
    }
  });



  function clearPage() {
    while (doc.firstChild) {
      doc.removeChild(doc.firstChild);
    }
  }

  function handleMessage(msg) {
    if (msg.clear)
      clearPage();
    else if (msg.base) {
      base = msg.base;
    } else
      mirror[msg.f].apply(mirror, msg.args);
  }

  // var socket = new WebSocket(receiverURL);
  var socket = io.connect(receiverURL);
  // console.log(socket,'socket');
  socket.on('connect', function() {

    socket.on('receiver', function(data) {

      // alert('ok')
      // console.log(data,'data')
      var msg = JSON.parse(data);
      if (msg instanceof Array) {
        msg.forEach(function(subMessage) {
          handleMessage(JSON.parse(subMessage));

        });
      } else {
        handleMessage(msg);
        // console.log($('#iframeId2').contents().find('body')[0]);
      }
    });

    socket.on('disconnect', function() {
      socket = new WebSocket(receiverURL);
    });
  })

});
